<template>
  <view class="interview-report-page">
    <navbar :showLeft="true" title="AI模拟面试" @leftClick="handleBack"></navbar>
    <view class="header" :style="{paddingTop: appInfoStore.getInfo().navBarHeight + 2*appInfoStore.getInfo().statusBar + 'px'}"></view>

    <!-- 主要内容区域 -->
    <scroll-view scroll-y class="content-container">
      <!-- 面试报告标题 -->
      <view class="report-title">面试报告</view>


      <view v-if="!loading">
        <!-- 总体评分模块 -->
      <view class="summary-card">
        <view class="score-circle">
          <text class="score-text">{{ reportData.totalScore.toFixed(1) }}</text>
        </view>
        <view class="rank-container">
          <text class="rank">{{ reportData.rank }}</text>
        <text class="interview-type">总体评分</text>
        </view>
      </view>

        <!-- 面试名称模块（新增） -->
        <view class="section-card">
          <view class="section-title">面试名称</view>
          <text class="section-content">{{ reportData.title }}</text>
        </view>

        <!-- 面试问题模块 -->
      <view class="section-card">
        <view class="section-title">面试问题</view>
          <view class="question-list">
            <view class="question-item" v-for="(item,index) in questions" :key="index">
              {{index+1}}、{{ item.question }}
             </view>
            </view>
          </view>

        <!-- 技能评估模块 -->
        <view class="section-card">
          <view class="section-title">技能评估</view>
          <text class="section-content">{{ reportData.skillEvaluation }}</text>
        </view>

        <!-- 技能评分详情模块 -->
        <view class="section-card">
          <view class="section-title">技能评分详情</view>
          <view
            class="skill-detail-item"
            v-for="(skill, index) in reportData.skills"
            :key="index"
          >
            <view class="skill-info">
              <text class="skill-name">{{ skill.name }}</text>
              <text class="score-text">{{ skill.score }}分</text>
            </view>
            <view class="progress-bar">
              <view
                class="progress-fill"
                :style="{ width: `${skill.percentage}%` }"
              ></view>
            </view>
          </view>
        </view>

        <!-- AI分析反馈模块 -->
        <view class="section-card">
          <view class="section-title">AI分析反馈</view>
          <view class="feedback-item">
            <view class="feedback-subtitle">优点</view>
            <view class="tags-container">
              <text
                class="tag advantage-tag"
                v-for="(tag, index) in reportData.advantages"
                :key="index"
              >
                {{ tag }}
              </text>
            </view>
          </view>
          <view class="feedback-item">
            <view class="feedback-subtitle">改进建议</view>
            <text class="suggestion-text">{{ reportData.improvementSuggestion }}</text>
          </view>
          <view class="feedback-item">
            <view class="feedback-subtitle">总体评价</view>
            <text class="evaluation-text">{{ reportData.overallEvaluation }}</text>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部操作按钮 -->
    <view class="action-buttons">
      <button class="action-btn secondary" @click="goToHome">返回首页</button>
      <button class="action-btn primary" @click="viewHistory">查看历史记录</button>
    </view>
  </view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import Api from "@/utils/Api.js";
import { useAppInfoStore } from "@/stores/appInfo";
import { ref, reactive, getCurrentInstance, nextTick } from "vue"
const { proxy } = getCurrentInstance();

const appInfoStore = useAppInfoStore();

const reportData = ref({
  totalScore: 0,
  rank: '',
  interviewType: '未知类型',
  title: '',
  question: '暂无问题',
  skillEvaluation: '暂无评估',
  skills: [],
  advantages: ['无'],
  improvementSuggestion: '暂无建议',
  overallEvaluation: '暂无评价'
});

const loading = ref(false);
const interviewId = ref('');

// 安全的返回方法
const handleBack = () => {
  const pages = getCurrentPages();
  if (pages.length > 1) {
    uni.navigateBack();
  } else {
    uni.switchTab({
      url: '/pages/home/HomeIndex'
    });
  }
};

const goToHome = () => {
  uni.switchTab({
    url: '/pages/home/HomeIndex'
  });
};

const viewHistory = () => {
  uni.navigateTo({
    url: '/pages/history/HistoryIndex'
  });
};

// 获取面试报告详情
const fetchReportDetail = async (id) => {
  try {
    loading.value = true;

    const url = `${Api.domain}${Api.loadReportDetail}?interviewId=${id}`;

    const res = await new Promise((resolve, reject) => {
      uni.request({
        url: url,
        method: 'GET',
        header: {
          'Content-Type': 'application/json',
          'token': uni.getStorageSync('token')
        },
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
    });

    if (res.statusCode === 200) {
      const data = res.data.data || {};
      
      // 计算四个技能分数的平均值
      const scores = [
        data.score1 || 0,
        data.score2 || 0,
        data.score3 || 0,
        data.score4 || 0
      ];
      const averageScore = Math.round(scores.reduce((sum, score) => sum + score, 0) / scores.length);
      
      // 根据平均分判断等级
      const getRank = (score) => {
        if (score >= 90) return '优秀';
        if (score >= 80) return '良好';
        if (score >= 70) return '中等';
        if (score >= 60) return '及格';
        return '不及格';
      };

      // 解析AI反馈JSON数据
      let aiFeedbackData = {};
      if (data.aiFeedback) {
        try {
          aiFeedbackData = JSON.parse(data.aiFeedback);
        } catch (e) {
          console.error('解析AI反馈失败:', e);
        }
      }

      // 处理优点数据
      const advantages = [];


      // 尝试从不同字段获取优点
      if (data.advantages && Array.isArray(data.advantages)) {
        advantages.push(...data.advantages);
      } else if (data.advantage) {
        advantages.push(data.advantage);
      } else if (data.Advantage1 || data.Advantage2 || data.Advantage3 || data.Advantage4) {
        if (data.advantage1) advantages.push(data.advantage1);
        if (data.advantage2) advantages.push(data.advantage2);
        if (data.advantage3) advantages.push(data.advantage3);
        if (data.advantage4) advantages.push(data.advantage4);
      } else if (aiFeedbackData.strengths) {
        advantages.push(...aiFeedbackData.strengths);
      }

      // 处理改进建议
      let improvementSuggestion = data.aiSuggestions ||  data.suggestion ||  (aiFeedbackData.weaknesses ? aiFeedbackData.weaknesses.join('；') : '暂无建议');

      // 处理总体评价
      let overallEvaluation = data.overallEvaluation ||  data.evaluation || 
                             (aiFeedbackData.summary ? aiFeedbackData.summary : '暂无评价');

      reportData.value = {
        totalScore: averageScore,
        rank: getRank(averageScore),
        interviewType: '技能评估',
        title: data.title || '未命名面试',
        question: data.question || '暂无问题',
        skillEvaluation: data.skillEvaluation || '暂无详细评估',
        skills: [
          { name: '表达能力', percentage: data.score1 || 0, score: data.score1 || 0 },
          { name: '逻辑思维', percentage: data.score2 || 0, score: data.score2 || 0 },
          { name: '专业知识', percentage: data.score3 || 0, score: data.score3 || 0 },
          { name: '沟通技巧', percentage: data.score4 || 0, score: data.score4 || 0 }
        ],
        advantages: advantages.length > 0 ? advantages : ['无'],
        improvementSuggestion: improvementSuggestion,
        overallEvaluation: overallEvaluation
      };
    } else {
      throw new Error(res.data?.msg || `请求失败，状态码: ${res.statusCode}`);
    }
  } catch (error) {
    console.error('获取报告出错:', error);
    uni.showToast({
      title: error.message.includes('Network') ? '网络连接失败' : '获取报告失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 加载问题
const questions=ref([]);
const loadQuestion=async(id)=>{
    const result = await proxy.Request({
          url:Api.selectQuestionByInterviewId+`?interviewId=${id}`,
          showLoading: false,
        });
        // 2. 检查响应数据
        if (!result){
            return;
        }
        questions.value=result;
}


onLoad((options) => {
   let interviewId= options.interviewId
  if (options?.interviewId) {
    fetchReportDetail(interviewId);
    loadQuestion(interviewId);
  } else {
    uni.showToast({
      title: '缺少面试ID参数',
      icon: 'none'
    });
    setTimeout(() => {
      const pages = getCurrentPages();
      if (pages.length > 1) {
        uni.navigateBack();
      } else {
        uni.switchTab({ url: '/pages/home/HomeIndex' });
      }
    }, 1500);
  }
});
</script>



<style lang="scss" scoped>
/* 基础样式 */
page {
  background-color: #f5f7fa;
  height: 100%;
}
.section-card {
  background: #fff;
  border-radius: 12rpx;
  padding: 25rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08);
}
.interview-report-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}


/* 问题列表样式 */
.question-list {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.question-item {
  color: #666;
  line-height: 1.6;
  font-size: 28rpx;
  padding-left: 10rpx;
}
.content-container {
  flex: 1;
  padding: 20rpx;
  overflow: hidden;
  box-sizing: border-box;
}

/* 报告标题 */
.report-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin: 20rpx 0 30rpx;
  margin-left: 3px;
  text-shadow: 0 2rpx 4rpx rgba(0,0,0,0.1);
}

/* 评分卡片 */
.summary-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08);
}

.score-circle {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background-color: rgb(208, 220, 230);
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 15rpx;
  box-shadow: 0 4rpx 8rpx rgba(0,0,0,0.1);
}

.score-text {
  color: blue;
  font-size: 48rpx;
  font-weight: bold;
  text-shadow: 0 2rpx 4rpx rgba(0,0,0,0.1);
}

.rank-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.rank {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 5rpx;
  text-shadow: 0 1rpx 2rpx rgba(0,0,0,0.1);
}

.interview-type {
  font-size: 26rpx;
  color: #999;
}

/* 内容卡片 */
.section-card {
  background: #fff;
  border-radius: 12rpx;
  padding: 25rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08);
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  padding-bottom: 15rpx;
  border-bottom: 1rpx solid #eee;
  text-shadow: 0 1rpx 2rpx rgba(0,0,0,0.1);
}

.section-content {
  color: #666;
  line-height: 1.6;
  font-size: 28rpx;
}

/* 技能详情 */
.skill-detail-item {
  margin-bottom: 25rpx;
  padding: 15rpx;
  background: #fff;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.05);
}

.skill-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.skill-name {
  font-size: 28rpx;
  color: #333;
}

.score-text {
  font-size: 26rpx;
  color: #1276F0;
  font-weight: bold;
}

.progress-bar {
  width: 100%;
  height: 10rpx;
  background-color: #f0f0f0;
  border-radius: 5rpx;
  overflow: hidden;
  box-shadow: inset 0 1rpx 2rpx rgba(0,0,0,0.1);
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #1276F0, #64b5f6);
  border-radius: 5rpx;
  transition: width 0.3s ease;
  box-shadow: 0 1rpx 3rpx rgba(0,0,0,0.2);
}

/* 反馈区域 */
.feedback-item {
  margin-bottom: 25rpx;
  padding: 15rpx;
  background: #fff;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.05);
}

.feedback-subtitle {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 15rpx;
  text-shadow: 0 1rpx 2rpx rgba(0,0,0,0.1);
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
}

.tag {
  padding: 6rpx 20rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
  line-height: 1.4;
  box-shadow: 0 1rpx 3rpx rgba(0,0,0,0.1);
}

.advantage-tag {
  background-color: rgba(18, 118, 240, 0.1);
  color: #1276F0;
}

.suggestion-text {
  display: inline-block;
  padding: 15rpx;
  background-color: #fff9f0;
  border-radius: 8rpx;
  color: #ff9500;
  font-size: 26rpx;
  line-height: 1.6;
  width: 100%;
  box-sizing: border-box;
  box-shadow: 0 1rpx 3rpx rgba(0,0,0,0.1);
  margin-bottom: 5px;
}

.evaluation-text {
  color: #666;
  line-height: 2.3;
  font-size: 28rpx;
  padding: 20rpx;
  border-radius: 8rpx;
}

/* 底部按钮 */
.action-buttons {
  display: flex;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.action-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  font-weight: 500;
  margin: 0 10rpx;
  margin-bottom: 5px;
  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.1);

  &.primary {
    background-color: #1276F0;
    color: #fff;

    &:active {
      background-color: #0d5cb8;
      box-shadow: 0 1rpx 3rpx rgba(0,0,0,0.2);
    }
  }

  &.secondary {
    background-color: #fff;
    color: #1276F0;
    border: 1px solid #1276F0;

    &:active {
      background-color: #f0f7ff;
      box-shadow: 0 1rpx 3rpx rgba(0,0,0,0.2);
    }
  }
}
</style>